package com.yeetrack.baidu.yinyueyun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jodd.http.HttpBrowser;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import jodd.io.FileUtil;
import jodd.io.NetUtil;
import jodd.util.URLDecoder;

import java.io.File;
import java.util.Set;

/**
 * Created by kongkong on 17/1/13.
 * blog: http://www.yeetrack.com
 * email: wangxuemeng90@126.com
 * 下载百度音乐收藏的音乐
 * 百度云音乐没有限制高清音乐,所以可以用此代码图片vip的限制,直接下载到高清音乐;已经把bug提供给了百度音乐,看看他们什么时间修复吧
 * add by kongkong on 18/3/26,百度云音乐已经下线了
 */
public class BaiduMain {
	private static final String cookieValue = "BAIDUID=82E1C320F19506649:FG=1; BIDUPSID=82E1C0F19506649; MCITY=-%3A; BDUSS=E0dUzhOUWo5Q1ZUb09rRXBXUzZXQ2xOMm0yNENMSFNSdEF6WHhZSVFBQUFBJCQAAAAAAAAAAAEAAACBIG8GeW91dGhmbGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAVVhAQFVYLV; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; PSINO=1; H_PS_PSSID=21870_1442_21080_17001; pgv_pvi=2972983296; pgv_si=s9773127680; Hm_lvt_2a05b2f5992616fb049897b06c=1484277620; Hm_lpvt_2a05b2f5992e16fb049897b06c=1484277620; cflag=15%3A3";
	public static void main(String[] args) {
		HttpBrowser httpBrowser = new HttpBrowser();
		httpBrowser.setDefaultHeader("Cookie", cookieValue);
		int pos = 0;
		while (true) {
			HttpRequest httpRequest = HttpRequest.get("http://yinyueyun.baidu.com/data/cloud/collection?type=song&start="+pos+"&size=200&_=1484277779810");
			HttpResponse httpResponse = httpBrowser.sendRequest(httpRequest);
			String songListString = httpResponse.bodyText();
			JSONObject responseJson = JSON.parseObject(songListString);
			JSONArray songJsonArray = responseJson.getJSONObject("data").getJSONArray("songList");
			System.out.println("song size: " + songJsonArray.size());
			pos += 200;
			if(songJsonArray.size() == 0) {
				break;
			}
			//解析歌曲详细信息
			int size = songJsonArray.size();
			for(int i=0; i<size; i++) {
				String songId = songJsonArray.getJSONObject(i).getString("id");
				//获取码率信息
				HttpRequest rateReq = HttpRequest.get("http://yinyueyun.baidu.com/data/cloud/download?songIds=" + songId);
				String rateString = httpBrowser.sendRequest(rateReq).bodyText();
				JSONObject rateJsonObject = JSON.parseObject(rateString);
				JSONObject dataJsonObject = rateJsonObject.getJSONObject("data").getJSONObject("data");
				Set<String> rateSet = dataJsonObject.keySet();
				String maxRate = "0";
				for(String rate : rateSet) {
					if("flac".equals(rate) || "original".equals(rate)) {
						continue;
					}
					try {
						JSONObject object = dataJsonObject.getJSONObject(rate);
						if (null == object || !object.getString("rate").equals(rate)) {
							continue;
						}
					} catch (Exception e) {
						continue;
					}

					if(maxRate.compareTo(rate) < 0) {
						maxRate = rate;
					}
				}
				if("0".equals(maxRate)) {
					System.out.println("码率获取失败, songId: " + songId);
					System.out.println(dataJsonObject.toString());
					continue;
				} else {
					String songUrl = "http://yinyueyun.baidu.com/data/cloud/downloadsongfile?songIds="+songId+"&rate=" + maxRate;
					HttpRequest downloadReq = HttpRequest.get(songUrl)
							.header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36")
							.header("Accept-Language", "en-US,en;q=0.5")
							.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
							.header("Accept-Encoding", "gzip, deflate")
							.header("Upgrade-Insecure-Requests", "1")
							.header("Cookie", cookieValue);
					HttpResponse downRes = httpBrowser.sendRequest(downloadReq);
					if(downRes.statusCode() >= 400) {
						System.out.println("Download failed, " + songId + ", " + maxRate);
					} else {
						String headerValue = downRes.header("content-disposition");
						if(null == headerValue) {
							continue;
						}
						int firstPos = headerValue.indexOf("\"");
						String fileName = headerValue.substring(firstPos+1, headerValue.indexOf("\"", firstPos+2));
						if(null == fileName || fileName.length() == 0) {
							continue;
						}
						fileName = URLDecoder.decode(fileName);
						File songFile = new File(fileName);
						if(songFile.exists()) {
							continue;
						}
						try {
							FileUtil.writeBytes(new File(fileName), downRes.bodyBytes());
							System.out.println(fileName + " download done!");
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							downRes.close();
						}
					}
				}
			}
		}
	}
}
